<template>
	<component
		v-if="column.search?.el"
		:is="`el-${column.search.el}`"
		v-bind="column.search.props"
		v-model="searchParam[column.search.key ?? handleProp(column.prop!)]"
		:data="column.search?.el === 'tree-select' ? columnEnum : []"
		:placeholder="placeholder(column)"
		:clearable="clearable(column)"
		range-separator="至"
		@change="changeForm"
		start-placeholder="开始时间"
		end-placeholder="结束时间"
	>
		<template v-if="column.search.el === 'select'">
			<component
				:is="`el-option`"
				v-for="(col, index) in columnEnum"
				:key="index"
				:label="col[fieldNames().label]"
				:value="col[fieldNames().value]"
			></component>
		</template>
		<template v-else-if="column.search.el === 'radio-group'">
			<component :is="`el-radio`" :value="col[fieldNames().value]" v-for="(col, index) in columnEnum" :key="index">{{
				col[fieldNames().label]
			}}</component>
		</template>
		<slot :name="`${column.prop}slot`"></slot>
	</component>
	<!-- 联动组件 -->
	<component
		v-if="column.search?.type === 'ZhyCascader'"
		:props="column.search?.props"
		:options="columnEnum"
		:formParam="searchParam"
		:column="column"
		v-bind="column.search.cascader"
		:is="ZhyCascader"
	></component>
</template>

<script setup lang="ts" name="searchFormItem">
import { computed, inject, ref } from 'vue';
import { handleProp } from '@/utils/util';
import { ColumnProps } from '@/components/ProTable/interface';
import { ZhyCascader } from '@/components';
interface SearchFormItem {
	column: ColumnProps; // 具体每一个搜索项的配置
	searchParam: { [key: string]: any }; // 搜索参数
}
const props = defineProps<SearchFormItem>();
// 接受 enumMap
const enumMap = inject('enumMap', ref(new Map()));

const columnEnum = computed(() => {
	if (!enumMap.value.get(props.column.prop)) return [];
	return enumMap.value.get(props.column.prop);
});

// 判断 fieldNames 设置 label && value 的 key 值
const fieldNames = () => {
	return {
		label: props.column.fieldNames?.label ?? 'label',
		value: props.column.fieldNames?.value ?? 'value'
	};
};

// 判断 placeholder
const placeholder = (column: ColumnProps) => {
	return column.search?.props?.placeholder ?? (column.search?.el === 'input' ? '请输入' : '请选择');
};

// 是否有清除按钮 (当搜索项有默认值时，清除按钮不显示)
const clearable = (column: ColumnProps) => {
	return column.search?.props?.clearable ?? (column.search?.defaultValue == null || column.search?.defaultValue == undefined);
};

// 派发change事件
const emits = defineEmits(['changeForm']);
const changeForm = (val?: any) => {
	emits('changeForm', val);
};
</script>
